/**
 * @author Francesco Rosso, matr 592057
 */

package pcd1112.model;

import java.util.ArrayList;

/**
 * This class has only a static method. When called, this class will wait until
 * all the nodes provided to that method are in a waiting or terminated signal.
 * (WARNING: active waiting)
 * 
 */
public class AwaitStop {

	private class Control extends Thread {
		private ArrayList<INodo> nodi;
		private final Object synchObj;
		boolean stop = false;

		public Control(ArrayList<INodo> nodi, Object synchObj) {
			this.nodi = nodi;
			this.synchObj = synchObj;
		}

		public boolean isStopped() {
			return stop;
		}

		public void run() {
			while (!stop) {
				int numDead = 0;
				for (int i = 0; i < nodi.size(); i++) {
					if ((nodi.get(i).getState() == State.WAITING)
							|| (nodi.get(i).getState() == State.TERMINATED))
						numDead++;
				}
				if (numDead == nodi.size()
						&& !Ambiente.getAmbiente().isPauseEverything()) {
					// if all the nodes are in a waiting or in a terminated
					// state, and the Ambiente is not in pause,
					// stop the thread and warn the hypervisor it can
					// stop this simulation step
					stop = true;
					synchronized (synchObj) {
						synchObj.notifyAll();
					}
				}
			}
		}
	}

	public static void await(ArrayList<INodo> nodi) {
		Object synchObj = new Object();
		AwaitStop a = new AwaitStop();
		AwaitStop.Control c = a.new Control(nodi, synchObj);
		c.start();
		try {
			synchronized (synchObj) {
				while (!c.isStopped()) {
					synchObj.wait();
				}
			}
		} catch (InterruptedException e) {
			// Auto-generated catch block
		}
	}
}
